//
//  ADView.m
//  HuiShangBaoApp
//
//  Created by chenzhihui on 13-8-16.
//  Copyright (c) 2013年 青岛晨之辉信息服务有限公司. All rights reserved.
//

#import "ADView.h"

#define ADIMAGEVIEWTAG 400
@implementation ADView

@synthesize startAnimation = _startAnimation;
@synthesize stopAnimation = _stopAnimation;
@synthesize horizontal = _horizontal;
@synthesize animationTime = _animationTime;
-(instancetype)init
{
    self = [super init];
    if (self) {
        {
            self.aDScrollView=[[UIScrollView alloc]init];
            [self addSubview:self.aDScrollView];
            MyPageControl *pageControl=[[MyPageControl alloc]init];
            self.pageControl=pageControl;
            [self addSubview:self.pageControl];
        }
    }
    return self;
}

-(void)loadADViewWithNumber:(NSInteger)num WithImageFrame:(CGSize)imageSize WithHorizontal:(BOOL)horizontal WithAnimationTime:(CGFloat)animationTime
{
    CGRect frame = self.frame;
    _num = num;
    _imageSize = imageSize;
    _horizontal = horizontal;
    _animationTime = animationTime;
    _currentPage = 1;
    _startAnimation = NO;
    CGFloat jianGeW = 0;
    _imageX = 0;
    _imageY = (frame.size.height - imageSize.height)/2.0;
//    self.aDScrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(jianGeW, 0, frame.size.width-jianGeW*2, imageSize.height)];
    self.aDScrollView.frame = CGRectMake(jianGeW, 0, frame.size.width-jianGeW*2, imageSize.height);
    self.aDScrollView.delegate = self;
    self.aDScrollView.showsHorizontalScrollIndicator = NO;
    self.aDScrollView.showsVerticalScrollIndicator = NO;
    self.aDScrollView.backgroundColor=[UIColor whiteColor];
    //按页滚动
    self.aDScrollView.pagingEnabled = YES;
    self.aDScrollView.clipsToBounds = NO;
   
    
    //设置是横向滚动还是纵向滚动
    if (YES == _horizontal)
    {
        self.aDScrollView.contentSize = CGSizeMake((self.aDScrollView.frame.size.width)*(num+2), frame.size.height);
        self.aDScrollView.contentOffset = CGPointMake(self.aDScrollView.frame.size.width, 0);
        
    }
    else
    {
        self.aDScrollView.contentSize = CGSizeMake(frame.size.width, frame.size.height*(num+2));
        self.aDScrollView.contentOffset = CGPointMake(0, frame.size.height);
    }
}
- (id)initWithFrame:(CGRect)frame WithNumber:(NSInteger)num WithImageFrame:(CGSize)imageSize WithHorizontal:(BOOL)horizontal WithAnimationTime:(CGFloat)animationTime
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.frame=frame;
        _num = num;
        _imageSize = imageSize;
        _horizontal = horizontal;
        _animationTime = animationTime;
        _currentPage = 1;
        _startAnimation = NO;
        CGFloat jianGeW = 0;
        _imageX = 0;
        _imageY = (frame.size.height - imageSize.height)/2.0;
        self.aDScrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(jianGeW, 0, frame.size.width-jianGeW*2, imageSize.height)];
        self.aDScrollView.delegate = self;
        self.aDScrollView.showsHorizontalScrollIndicator = NO;
        self.aDScrollView.showsVerticalScrollIndicator = NO;
        self.aDScrollView.backgroundColor=[UIColor whiteColor];
        //按页滚动
        self.aDScrollView.pagingEnabled = YES;
        self.aDScrollView.clipsToBounds = NO;
        //设置是横向滚动还是纵向滚动
        if (YES == _horizontal)
        {
            self.aDScrollView.contentSize = CGSizeMake((self.aDScrollView.frame.size.width)*(num+2), frame.size.height);
            self.aDScrollView.contentOffset = CGPointMake(self.aDScrollView.frame.size.width, 0);
            
        }
        else
        {
            self.aDScrollView.contentSize = CGSizeMake(frame.size.width, frame.size.height*(num+2));
            self.aDScrollView.contentOffset = CGPointMake(0, frame.size.height);
        }
        [self addSubview:self.aDScrollView];
    }
    return self;
}
-(void)addPageControl{//
    
    self.pageControl.backgroundColor = [UIColor clearColor];
    self.pageControl.userInteractionEnabled = NO;
    self.pageControl.numberOfPages = _num;
//    [self.pageControl sizeToFit];
    self.pageControl.frame =CGRectMake(0, _imageSize.height-20, self.aDScrollView.frame.size.width, 20);
    
    self.pageControl.otherColor = PAGE_while_Current_COLOR;
    self.pageControl.currentColor = PAGE_while_Current_COLOR;
    
    
    
}
#pragma mark - 设置广告信息栏
- (void)initAdImageView:(NSString *)title WithFrame:(CGRect)frame WithView:(id)view WithTitleColor:(UIColor *)color WithFont:(UIFont *)font
{
    UIImageView *noticeImgView = [[UIImageView alloc] initWithFrame:frame];
    noticeImgView.image = (UIImage *)[UIColor redColor];
    [view addSubview:noticeImgView];
    
    UILabel *tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
    tempLabel.text = title;
    tempLabel.textAlignment = NSTextAlignmentCenter;
    tempLabel.backgroundColor = [UIColor clearColor];
    tempLabel.textColor = color;
    tempLabel.font = font;
    [noticeImgView addSubview:tempLabel];
}

#pragma mark - 开启定时器循环滚动
- (void)startAnimation:(BOOL)start
{
    _startAnimation = start;
    if (_num > 1)       //两张图以上，才进行左右滚动
    {
        if (YES == start)     //开始动画
        {
            [self timeFire];
        }
        else        //结束动画
        {
            [self timeInvalidate];
        }
    }
}

//销毁定时器
- (void)timeInvalidate
{
    if (_timer)
    {
        [_timer invalidate];
        _timer = nil;
    }
}

//开启定时器
- (void)timeFire
{
    if (!_timer) {
        _timer=[NSTimer timerWithTimeInterval:_animationTime target:self selector:@selector(adViewScrollAction:) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
    }
}

//定时器触发方法
- (void)adViewScrollAction:(id)object
{
    _currentPage += 1;
    if (2+_num == _currentPage) //判断如果滚动到最后一张，就从第二张开始
    {
        _currentPage = 2;
        
    }
    
    if (YES == _horizontal) {
        [self.aDScrollView setContentOffset:CGPointMake(_currentPage*self.aDScrollView.frame.size.width, 0) animated:YES];
        
    }
    else
    {
        [self.aDScrollView setContentOffset:CGPointMake(0, _currentPage*self.frame.size.height) animated:YES];
        
    }
    
    
}

#pragma mark - 加载图片
-(NSMutableArray *)imageViewArray
{
    if (!_imageViewArray) {
        
        _imageViewArray = [[NSMutableArray alloc]init];
        for (int i = 0; i <= _num+1; i ++) {
            UIImageView *image = [[UIImageView alloc] init];
//            image.backgroundColor = [UIColor redColor];
            [self.aDScrollView addSubview:image];
            [_imageViewArray addObject:image];
        }
    }
    
    return _imageViewArray;
}

- (void)initImageViewWithImagesURL:(NSArray *)imagesURL andPlaceholderImageName:(NSString *)placeholderName
{
    for (int i = 0; i <= self.imageViewArray.count; i++) {
        UIImageView *imageView = [_imageViewArray objectAtIndex:i];
        NSString *tempImageName = nil;
        if (i == _num+1) {
            tempImageName = [imagesURL objectAtIndex:0];
        }
        else if (i == 0)
        {
            tempImageName = [imagesURL objectAtIndex:_num-1];
        }
        else
            tempImageName = [imagesURL objectAtIndex:i-1];
        
        if (YES == _horizontal)
        {
            imageView.frame = CGRectMake(_imageX+i*self.frame.size.width, _imageY, _imageSize.width, _imageSize.height);
        }
        else
        {
            imageView.frame = CGRectMake(_imageX, _imageY+i*self.frame.size.height, _imageSize.width, _imageSize.height);
        }
        imageView.tag = ADIMAGEVIEWTAG+i;
        NSURL *imageURL = [NSURL URLWithString:tempImageName];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        [imageView sd_setImageWithURL:imageURL placeholderImage:[UIImage imageNamed:placeholderName] options:(SDWebImageRetryFailed)];
        imageView.userInteractionEnabled = YES;
//        [self.aDScrollView addSubview:imageView];
        
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickOnImageView:)];
        [imageView addGestureRecognizer:tapGesture];
    }
}


//图片不适应自身大小
- (void)initNOFitImageViewWithImagesURL:(NSArray *)imagesURL andPlaceholderImageName:(NSString *)placeholderName
{
    self.halfGap = 0;
    UIImageView * l_image = nil;
    for (int i = 0; i < self.imageViewArray.count; i++) {
        UIImageView *imageView = [_imageViewArray objectAtIndex:i];
//        imageView.backgroundColor = _imageColor;
        NSString *tempImageName = nil;
        if (i == _num+1) {
            tempImageName = [imagesURL objectAtIndex:0];
        }
        else if (i == 0)
        {
            tempImageName = [imagesURL objectAtIndex:_num-1];
        }
        else
            tempImageName = [imagesURL objectAtIndex:i-1];
        
        if (YES == _horizontal)
        {
            CGFloat viewW = self.aDScrollView.frame.size.width - 2 * self.halfGap;
            imageView.frame = CGRectMake((2 * i + 1) * self.halfGap + i * viewW, 0, viewW, _imageSize.height);
        }
        else
        {
            imageView.frame = CGRectMake(_imageX, _imageY+i*self.frame.size.height, _imageSize.width, _imageSize.height);
        }
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        imageView.tag = ADIMAGEVIEWTAG+i;
//        imageView.backgroundColor = ZHU_Color;
        NSURL *imageURL = [NSURL URLWithString:tempImageName];
        [imageView sd_setImageWithURL:imageURL placeholderImage:[UIImage imageNamed:tempImageName] options:(SDWebImageRetryFailed)];
        imageView.userInteractionEnabled = YES;
        l_image = imageView;
        
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickOnImageView:)];
        [imageView addGestureRecognizer:tapGesture];
    }
}

- (void)initImageViewWithImageNames:(NSArray *)imageNames
{
    for (int i = 0; i < _num+2; i++) {
        UIImageView *imageView = [[UIImageView alloc] init];
        NSString *tempImageName = nil;
        //如果加载到最后一条数据，将第一条数据，赋给最后一条数据
        if (i == _num+1) {
            tempImageName = [imageNames objectAtIndex:0];
        }
        else if (i == 0)
        {
            tempImageName = [imageNames objectAtIndex:_num-1];
        }
        else
            tempImageName = [imageNames objectAtIndex:i-1];
        
        if (YES == _horizontal)
        {
            imageView.frame = CGRectMake(i*(_imageSize.width+10), _imageY, _imageSize.width, _imageSize.height);
        }
        else
        {
            imageView.frame = CGRectMake(_imageX, _imageY+i*self.frame.size.height, _imageSize.width, _imageSize.height);
        }
        imageView.tag = ADIMAGEVIEWTAG+i;
        imageView.image = [UIImage imageNamed:tempImageName];
        imageView.userInteractionEnabled = YES;
        [self.aDScrollView addSubview:imageView];
        
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickOnImageView:)];
        [imageView addGestureRecognizer:tapGesture];
    }
}

#pragma mark - 对外暴露点击事件
- (void)clickOneImage:(ScrollViewTouch)touchBlock
{
    //ARC下如此调用即可
    _touchBlock = touchBlock;
}

#pragma mark - 手势点击事件
//点击事件
- (void)clickOnImageView:(UITapGestureRecognizer *)tap
{
    UIImageView *tempImgView = (UIImageView *)tap.view;
    NSInteger tempIndex = tempImgView.tag - ADIMAGEVIEWTAG;
    
    if (tempIndex == 0) {
        tempIndex = _num-1;
    }
    else if (tempIndex == _num+1)
    {
        tempIndex = 0;
    }
    else
        tempIndex = tempIndex-1;
    
    if (_touchBlock) {
        _touchBlock(tempIndex);
    }
    
    
}

#pragma mark - UIScrollView Delegate
//判断滚动，如果是最后一张图，跳转到第二张图，如果是第一张图，跳转到倒数第二张图
- (void)scrollViewDidScroll:(UIScrollView *)scrollView;
{
   
    //临界点
    if (YES == _horizontal) {
        if (scrollView.contentOffset.x >= (_num+0.99)*self.aDScrollView.frame.size.width)
        {

            [scrollView setContentOffset:CGPointMake(self.aDScrollView.frame.size.width, 0)];
             
            
        } else if (scrollView.contentOffset.x == 0) {

            [scrollView setContentOffset:CGPointMake(_num*self.aDScrollView.frame.size.width, 0)];
            
        }else{
            int newPage=scrollView.contentOffset.x/self.aDScrollView.frame.size.width-0.99;
            [self.pageControl setCurrentPage:newPage];
            _currentPage=newPage;

        }
    
    }
    else
    {
        if (scrollView.contentOffset.y == (_num+1)*self.aDScrollView.frame.size.height)
        {
            [scrollView setContentOffset:CGPointMake(0, self.aDScrollView.frame.size.height)];
        }
        if (scrollView.contentOffset.y == 0) {
            [scrollView setContentOffset:CGPointMake(0, _num*self.aDScrollView.frame.size.height)];
        }
        
    }
}

//开始滑动是，关闭定时器
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self timeInvalidate];
}
//滑动结束后，开启定时器
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (_startAnimation) {
       [self timeFire];
    }else{
       [self timeInvalidate];
    }
    
    
}
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    if (_startAnimation) {
        [self timeFire];
    }else{
        [self timeInvalidate];
    }
}


@end
